<template>
  <div>
    <h2>登录</h2>
    <div>
      <el-form
        :label-position="'left'"
        label-width="auto"
        :model="formData"
        style="max-width: 600px"
      >
        <el-form-item label="用户名">
          <el-input v-model="formData.username" />
        </el-form-item>
        <el-form-item label="密码">
          <el-input v-model="formData.password" />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="loginHandler"> 登录 </el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script lang="ts">
export default {
  name: 'study6Login'
}
</script>

<script setup lang="ts">
import { reactive } from 'vue'

import { type IUserLoginInfo, apiLogin } from '@/service/study5/demo2'
import { useRoute, useRouter } from 'vue-router'
import type { LocationQuery } from 'vue-router'

const router = useRouter()
const route = useRoute()

const formData: IUserLoginInfo = reactive({
  username: '',
  password: ''
})

// 执行登录
const loginHandler = async () => {
  try {
    const resData = await apiLogin(formData)

    if (resData.code !== '2000' || !resData.data) {
      throw new Error(resData.msg || '未知错误')
    }
    // 登录成功
    localStorage.setItem('token', resData.data)

    localStorage.setItem('token', '123456')

    setTimeout(() => {
      // router.replace({ path: '/studemo62/user' })
      const { path, queryParams } = parseRedirect()
      router.push({ path: path, query: queryParams })
    }, 12)
  } catch (e: any) {
    alert((e as Error).message)
  }
}

/** 解析 redirect 字符串 为 path 和  queryParams */
function parseRedirect(): {
  path: string
  queryParams: Record<string, string>
} {
  const query: LocationQuery = route.query
  const redirect = (query.redirect as string) ?? '/'

  const url = new URL(redirect, window.location.origin)
  const path = url.pathname
  const queryParams: Record<string, string> = {}

  url.searchParams.forEach((value, key) => {
    queryParams[key] = value
  })

  return { path, queryParams }
}
</script>

<style></style>
